package com.fresh.bus.chat.business;

import java.util.HashMap;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import com.fresh.bus.canoe.message.Response;
import com.fresh.bus.canoe.session.Session;
import com.fresh.bus.canoe.session.SessionRoleManager;
import com.fresh.bus.chat.ctrl.OpCodes;

@Component
public class EnergyService {

	public static final int GATHER_WATER_ENERGY = -20; //取水
	public static final int POURE_WATER_ENERGY = -5; //浇水
	public static final int WRITE_FEIJI_ENERGY = -60; //纸飞机
	
	private static final Logger log = LoggerFactory
			.getLogger(EnergyService.class);

	private StringRedisTemplate template;
	@Resource
	private UserService userService;
	@Resource
	protected SessionRoleManager roleManager;

	@Autowired
	public EnergyService(StringRedisTemplate template) {
		this.template = template;
	}
	
	public void update(String userId, int value){
		String uid = KeyUtils.uid(userId);
		BoundHashOperations<String, String, String> ops = template
				.boundHashOps(uid);
		int energy = Integer.valueOf(ops.get("energy"));
		energy += value;
		if(energy>100) energy = 100;
		if(energy<0) energy = 0;
		ops.put("energy", String.valueOf(energy));
		sendResponse(userId,energy);
	}
	
	public boolean valid(String userId, int value){
		String uid = KeyUtils.uid(userId);
		BoundHashOperations<String, String, String> ops = template
				.boundHashOps(uid);
		int energy = Integer.valueOf(ops.get("energy"));
		energy += value;
		return energy > 0;
	}	
	
	public void restore(String userId){
		String uid = KeyUtils.uid(userId);
		BoundHashOperations<String, String, String> ops = template
				.boundHashOps(uid);
		ops.put("energy", "100");
		sendResponse(userId,100);
	}	

	private void sendResponse(String userId, int value) {
		Response response;
		Session session = this.roleManager.getSession(userId);
		if (session != null) {
			response = new Response(OpCodes.SYN_ENERGY);
			response.setData(value);
			session.send(response);
		}
	}
}
